//
//  ViewController.swift
//  day08
//
//  Created by 杨绍鑫 on 2018/9/20.
//  Copyright © 2018年 crcnet. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVAudioPlayer()
    
    let grdLayer : CAGradientLayer = {
        
        let grdLayer = CAGradientLayer()
        let color1 = UIColor(white: 0.5, alpha: 0.2).cgColor as CGColor
        let color2 = UIColor(red: 1.0, green: 0, blue: 0, alpha: 0.4).cgColor as CGColor
        let color3 = UIColor(red: 0, green: 1, blue: 0, alpha: 0.3).cgColor as CGColor
        let color4 = UIColor(red: 0, green: 0, blue: 1, alpha: 0.3).cgColor as CGColor
        let color5 = UIColor(white: 0.4, alpha: 0.2).cgColor as CGColor
        
        grdLayer.colors = [color1, color2, color3, color4, color5]
        grdLayer.locations = [0.10, 0.30, 0.50, 0.70, 0.90]
        grdLayer.startPoint = CGPoint(x: 0, y: 0)
        grdLayer.endPoint = CGPoint(x: 1, y: 1)
        return grdLayer
        
    }()
    
    var timer = Timer()
    
    
    @IBOutlet weak var bgView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.grdLayer.frame = self.view.frame

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //MARK: -
    
    @IBAction func payMusic(_ sender: UIButton) {
        
        self.bgView.layer.addSublayer(grdLayer)
        
        let musicPath = URL.init(fileURLWithPath: Bundle.main.path(forResource: "Ecstasy", ofType: "mp3")!)
        
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            try player = AVAudioPlayer.init(contentsOf: musicPath)
            player.prepareToPlay()
            player.play()
            print("playing-----")
        } catch let audioError as NSError {
            print(audioError)
        }
        self.timer.invalidate()
        self.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { (t) in
            self.chanageColor()
        })
        timer.fire()
    }
    
    func randomColor()->UIColor {
        let red = CGFloat(drand48())
        let greed = CGFloat(drand48())
        let blue = CGFloat(drand48())
        
        let color = UIColor.init(red: red, green: greed, blue: blue, alpha: 1)
        return color
    }
    
    func chanageColor()  {
        self.bgView.backgroundColor = randomColor()
    }
    

}

